/**
 * Copyright(C): CETC-32
 * @Description: 字符串日期转换
 * @author: youqing
 * @version: 1.0
 * @date: 2020/10/11 10:55
 * 更改描述：
 */
package com.cetc32.dh.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @Title: StringToDateConverter
 * @Description:
 * @author: youqing
 * @version: 1.0
 * @date: 2020/10/13 11:19
 */
@Slf4j
public class StringToDateConverter implements Converter<String, Date> {

    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";
    private static final String shortTimeFormat="HH:mm:ss";

    /**
     * 指定缓存失效时间
     * @param value
     * @return Date
     */
    @Override
    public Date convert(String value) {

        if(value == null || "".equals(value)) {
            return null;
        }

        value = value.trim();

        try {
            if(value.contains("-")) {
                SimpleDateFormat formatter;
                if(value.contains(":")) {
                    formatter = new SimpleDateFormat(dateFormat);
                }else {
                    formatter = new SimpleDateFormat(shortDateFormat);
                }

                Date dtDate = formatter.parse(value);
                return dtDate;
            }else if(value.matches("^\\d+$")) {
                Long lDate = new Long(value);
                return new Date(lDate);
            }else if(value.contains(":")){
                SimpleDateFormat formatter = new SimpleDateFormat(shortTimeFormat);
                return formatter.parse(value);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("转换日期：%s 异常", value));
        }
        throw new RuntimeException(String.format("转换日期：%s 异常", value));
    }


    /*@Override
    public Date convert(String source) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(source);
        } catch (ParseException e) {
            log.error("日期转化异常：" + source,e);
        }
        return null;
    }*/
}
